let currentData = [];
let currentPage = 1;
let pageSize = 10;
let currentChart = null;

async function loadNodeData() {
    const nodeType = document.getElementById('nodeTypeSelect').value;
    if (!nodeType) return;

    try {
        const response = await fetch(`/api/nodes/${nodeType}`);
        const result = await response.json();
        
        if (!result.success) {
            alert(result.message);
            return;
        }

        currentData = result.data.nodes;
        renderChart(currentData);
        renderTable(1);
    } catch (error) {
        console.error('加载节点数据出错:', error);
        alert('加载节点数据时出现错误，请稍后重试');
    }
}

function renderChart(data) {
    const chartContainer = document.getElementById('chartContainer');
    chartContainer.innerHTML = '<canvas id="dataChart"></canvas>';
    const ctx = document.getElementById('dataChart').getContext('2d');
    
    // 销毁现有图表
    if (currentChart) {
        currentChart.destroy();
    }

    const nodeType = document.getElementById('nodeTypeSelect').value;
    
    switch(nodeType) {
        case 'Artifact':
            renderArtifactChart(ctx, data);
            break;
        case 'Caizhi':
            renderCaizhiChart(ctx, data);
            break;
        case 'CulturalItem':
            renderCulturalItemChart(ctx, data);
            break;
        case 'Image1':
            renderImageChart(ctx, data);
            break;
        case 'InstrumentGene':
            renderInstrumentChart(ctx, data);
            break;
    }
}

function renderArtifactChart(ctx, data) {
    const artifactTypes = {};
    data.forEach(item => {
        const type = item.properties.code || '未分类';
        artifactTypes[type] = (artifactTypes[type] || 0) + 1;
    });

    currentChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: Object.keys(artifactTypes),
            datasets: [{
                label: '文物基因分布',
                data: Object.values(artifactTypes),
                backgroundColor: 'rgba(54, 162, 235, 0.5)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: '数量'
                    }
                }
            }
        }
    });
}

function renderCaizhiChart(ctx, data) {
    const caizhiStats = {};
    data.forEach(item => {
        const type = item.properties.cz_name || '未知材质';
        caizhiStats[type] = (caizhiStats[type] || 0) + 1;
    });

    currentChart = new Chart(ctx, {
        type: 'pie',
        data: {
            labels: Object.keys(caizhiStats),
            datasets: [{
                data: Object.values(caizhiStats),
                backgroundColor: [
                    'rgba(255, 99, 132, 0.5)',
                    'rgba(54, 162, 235, 0.5)',
                    'rgba(255, 206, 86, 0.5)',
                    'rgba(75, 192, 192, 0.5)',
                    'rgba(153, 102, 255, 0.5)'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right'
                },
                title: {
                    display: true,
                    text: '材质分布'
                }
            }
        }
    });
}

function renderCulturalItemChart(ctx, data) {
    const periodStats = {};
    data.forEach(item => {
        const period = item.properties.period || '未知年代';
        periodStats[period] = (periodStats[period] || 0) + 1;
    });

    currentChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: Object.keys(periodStats),
            datasets: [{
                label: '文物时期分布',
                data: Object.values(periodStats),
                fill: false,
                borderColor: 'rgb(75, 192, 192)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: '数量'
                    }
                }
            }
        }
    });
}

function renderImageChart(ctx, data) {
    const dimensions = data.map(item => ({
        x: parseFloat(item.properties.chang) || 0,
        y: parseFloat(item.properties.kuan) || 0
    }));

    currentChart = new Chart(ctx, {
        type: 'scatter',
        data: {
            datasets: [{
                label: '图片尺寸分布',
                data: dimensions,
                backgroundColor: 'rgba(255, 99, 132, 0.5)'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                x: {
                    title: {
                        display: true,
                        text: '长度'
                    }
                },
                y: {
                    title: {
                        display: true,
                        text: '宽度'
                    }
                }
            }
        }
    });
}

function renderInstrumentChart(ctx, data) {
    const instrumentTypes = {};
    data.forEach(item => {
        const type = item.properties.name || '未知器型';
        instrumentTypes[type] = (instrumentTypes[type] || 0) + 1;
    });

    currentChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: Object.keys(instrumentTypes),
            datasets: [{
                data: Object.values(instrumentTypes),
                backgroundColor: [
                    'rgba(255, 99, 132, 0.5)',
                    'rgba(54, 162, 235, 0.5)',
                    'rgba(255, 206, 86, 0.5)',
                    'rgba(75, 192, 192, 0.5)',
                    'rgba(153, 102, 255, 0.5)'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right'
                },
                title: {
                    display: true,
                    text: '器型分布'
                }
            }
        }
    });
}

function renderTable(page) {
    currentPage = page;
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const pageData = currentData.slice(start, end);

    // 渲染表头
    const tableHeader = document.getElementById('tableHeader');
    if (currentData.length > 0) {
        // 使用第一条数据的 properties 作为表头
        const headers = Object.keys(currentData[0].properties);
        tableHeader.innerHTML = headers.map(header => 
            `<th class="px-4 py-2 bg-gray-100">${header}</th>`
        ).join('');
    }

    // 渲染表体
    const tbody = document.getElementById('tableBody');
    tbody.innerHTML = pageData.map(item => `
        <tr class="hover:bg-gray-50">
            ${Object.entries(item.properties).map(([key, value]) => 
                `<td class="px-4 py-2 border-b" title="${value || '-'}">${value || '-'}</td>`
            ).join('')}
        </tr>
    `).join('');

    renderPagination();
}

function renderPagination() {
    const totalPages = Math.ceil(currentData.length / pageSize);
    const pagination = document.getElementById('pagination');
    
    let paginationHtml = `
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="event.preventDefault(); ${currentPage > 1 ? `renderTable(${currentPage - 1})` : ''}">&laquo;</a>
        </li>
    `;

    // 显示当前页码前后各两页
    for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
        paginationHtml += `
            <li class="page-item ${currentPage === i ? 'active' : ''}">
                <a class="page-link" href="#" onclick="event.preventDefault(); renderTable(${i})">${i}</a>
            </li>
        `;
    }

    paginationHtml += `
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="event.preventDefault(); ${currentPage < totalPages ? `renderTable(${currentPage + 1})` : ''}">&raquo;</a>
        </li>
    `;

    pagination.innerHTML = paginationHtml;
}

function changePageSize() {
    pageSize = parseInt(document.getElementById('pageSizeSelect').value);
    renderTable(1);
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    const nodeTypeSelect = document.getElementById('nodeTypeSelect');
    if (nodeTypeSelect.value) {
        loadNodeData();
    }
});

// 在创建表格单元格时添加以下处理
function createTableCell(content) {
    const td = document.createElement('td');
    td.textContent = content;
    // 为单元格添加title属性，方便鼠标悬停时显示完整内容
    td.title = content;
    return td;
}

// 在加载数据时使用这个函数
// 修改原有的 loadNodeData 函数
async function loadNodeData() {
    const nodeType = document.getElementById('nodeTypeSelect').value;
    if (!nodeType) return;

    try {
        const response = await fetch(`/api/nodes/${nodeType}`);
        const result = await response.json();
        
        if (!result.success) {
            alert(result.message);
            return;
        }

        currentData = result.data.nodes;
        
        // 修改表格渲染逻辑，使用 createTableCell 函数
        renderChart(currentData);
        renderTableWithFormat(1);
    } catch (error) {
        console.error('加载节点数据出错:', error);
        alert('加载节点数据时出现错误，请稍后重试');
    }
}

// 添加新的表格渲染函数
function renderTableWithFormat(page) {
    currentPage = page;
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const pageData = currentData.slice(start, end);

    // 渲染表头
    const tableHeader = document.getElementById('tableHeader');
    if (currentData.length > 0) {
        const headers = Object.keys(currentData[0].properties);
        tableHeader.innerHTML = headers.map(header => 
            `<th class="px-4 py-2 bg-gray-100">${header}</th>`
        ).join('');
    }

    // 渲染表体
    const tbody = document.getElementById('tableBody');
    tbody.innerHTML = '';
    
    pageData.forEach(item => {
        const row = document.createElement('tr');
        row.className = 'hover:bg-gray-50';
        
        Object.values(item.properties).forEach(value => {
            row.appendChild(createTableCell(value || '-'));
        });
        
        tbody.appendChild(row);
    });

    renderPagination();
}

// 删除重复的 loadNodeData 函数